package com.hboxs.asl.controller.app.member;

import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.controller.app.BaseController;
import com.hboxs.asl.entity.Area;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.entity.Receiver;
import com.hboxs.asl.service.AreaService;
import com.hboxs.asl.service.MemberService;
import com.hboxs.asl.service.ReceiverService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Set;

/**
 * Created by hboxs002 on 2016/10/20.
 * Controller -- 收货地址
 */
@Controller(value = "appMemberReceiverController")
@RequestMapping(value = "/app/m/receiver")
public class ReceiverControl extends BaseController {

    protected Logger logger = Logger.getLogger(getClass().getName());

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "receiverServiceImpl")
    private ReceiverService receiverService;
    @Resource(name = "areaServiceImpl")
    private AreaService areaService;

    /**
     * 我的收货地址
     *
     * @return JsonMessage
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage myReceiver() {
        try {
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Set<Receiver> receivers = member.getReceivers();

            return JsonMessage.success(
                    JsonMessage.optimiseObj(
                            receivers,
                            "id", "consignee", "areaName", "area.id", "address", "zipCode", "phone", "isDefault"
                    )
            );
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 添加收货地址
     *
     * @return JsonMessage
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage addReceiver(Receiver receiver, Long areaId) {
        try {
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            if (Receiver.MAX_RECEIVER_COUNT != null && member.getReceivers().size() >= Receiver.MAX_RECEIVER_COUNT) {
                return JsonMessage.error("收货地址已经满了，请删除后再添加");
            }
            if (receiver.getConsignee() == null) {
                return JsonMessage.error("收货人不能为空");
            }
            if (receiver.getPhone() == null) {
                return JsonMessage.error("手机号码不能为空");
            }
            if (receiver.getAddress() == null) {
                return JsonMessage.error("详细地址不能为空");
            }
            if (receiver.getZipCode() == null) {
                return JsonMessage.error("邮政编码不能为空");
            }
            Area area = areaService.find(areaId);
            if (area == null) {
                return JsonMessage.error("地区不能为空");
            }

            receiver.setMember(member);
            receiver.setIsDefault(false);
            receiver.setArea(area);
            receiverService.save(receiver);

            return JsonMessage.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 编辑收货地址
     *
     * @return JsonMessage
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage editReceiver(Receiver receiver, Long areaId) {
        try {
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            if (receiver.getId() == null) {
                return JsonMessage.error("收货地址id不能为空");
            }
            if (receiver.getConsignee() == null) {
                return JsonMessage.error("收货人姓名不能为空");
            }
            if (receiver.getPhone() == null) {
                return JsonMessage.error("手机号码不能为空");
            }
            Area area = areaService.find(areaId);
            if (area == null) {
                return JsonMessage.error("地区不能为空");
            }
            if (receiver.getAddress()== null) {
                return JsonMessage.error("详细地址不能为空");
            }
            if (receiver.getZipCode()== null) {
                return JsonMessage.error("邮政编码不能为空");
            }

            receiver.setArea(area);

            receiverService.update(receiver,"isDefault","createDate","member");

            return JsonMessage.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 删除收货地址
     *
     * @return JsonMessage
     */
    @RequestMapping(value = "/del", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage delReceiver(Long id) {
        try {
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Receiver receiver = receiverService.find(id);
            if (receiver == null || !member.equals(receiver.getMember())) {
                return JsonMessage.error("该收货地址不存在");
            }
            receiverService.delete(id);

            return JsonMessage.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 设置默认值
     */
    @RequestMapping(value = "/def_set", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage isDefault(Long id) {
        try {
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            Set<Receiver> receivers = member.getReceivers();
            if (receivers.size() <= 0) {
                return JsonMessage.error("请添加收货地址");
            }
            Receiver receiver = receiverService.find(id);
            if (receiver == null) {
                return JsonMessage.error("该收货地址不存在");
            }
            if (!receiver.getIsDefault()) {
                for (Receiver pReceiver : receivers) {
                    pReceiver.setIsDefault(false);
                }
                receiver.setIsDefault(true);
                receiverService.update(receiver);
                return JsonMessage.success("设置默认值");
            } else {
                receiver.setIsDefault(false);
                receiverService.update(receiver);
                return JsonMessage.success("取消默认值");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

}
